from . import api
from .. import db
from .authentication import auth
from ..utils.aliyunVideo import init_vod_client, get_play_info
from ..models import *
from .lovePost import getVideo
from flask import request, jsonify, g
import traceback

# √
# 发布评论
@api.route('/loveComment', methods=['POST'])
def upload_love_comment():
    # 生成love_post_comment对象，并插入到表中
    print('[+] add love comment: %s' % request.json)
    love_comment = loveComment.from_json(request.json)
    try:
        db.session.add(love_comment)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error='Upload love comment failed!', detail=traceback.format_exc())
        response.status_code = 403
        return response

    print('[+] Add love comment: %r' % love_comment.love_post_comment_id)
    response = jsonify(message='Upload love comment successfully!')
    response.status_code = 200
    return response

# √
# 删除自己的评论
@api.route('/loveComment/<lovePostCommentId>', methods=['DELETE'])
def delete_love_comment(lovePostCommentId):
    love_comment = loveComment.query.get_or_404(lovePostCommentId)

    if g.current_user.user_id != love_comment.user_id:
        response = jsonify(error="forbidden!", detail="You can't delete other user's loveComment!")
        response.status_code = 403
        return response

    try:
        db.session.delete(love_comment)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error="Delete this love comment failed!", detail=traceback.format_exc())
        response.status_code = 403
        return response

    print('[-] Delete love comment: %r' % love_comment.love_post_comment_id)
    response = jsonify(message='Delete love comment: %r successfully!' % lovePostCommentId)
    response.status_code = 200
    return response

# √
# 查看表白墙详细信息
@api.route('/loveComment/<lovePostId>', methods=['GET'])
def get_love_comments(lovePostId):
    user = User.query.get_or_404(g.current_user.user_id)
    love_post = lovePost.query.get_or_404(lovePostId)
    love_post_user = User.query.get_or_404(love_post.user_id)
    love_post_user_fans = follows.query.filter(follows.user_id==love_post_user.user_id, \
                                                follows.fans_id==g.current_user.user_id).first()
    
    page = request.args.get("page") if request.args.get("page") else 1
    pageSize = request.args.get("pageSize") if request.args.get("pageSize") else 20
    love_comment = loveComment.query.filter_by(love_post_id=lovePostId).order_by(loveComment.publish_time).paginate(int(page), int(pageSize), False).items

    u_collection = userCollection.query.filter(userCollection.user_id==g.current_user.user_id, \
                                                userCollection.love_post_id==lovePostId).first()
    u_love_post_like = userLovePostLike.query.filter(userLovePostLike.user_id==g.current_user.user_id, \
                                                        userLovePostLike.love_post_id==lovePostId).first()

    imgUrls = []

    if love_post.media_type == 'img':
        imgUrls = [img.img_url for img in love_post.images]

    love_post = love_post.to_json()
    love_post_user = love_post_user.to_json()

    if love_post['media_type'] == 'img':
        love_post['imgUrls'] = imgUrls
    if love_post['media_type'] == 'video':
            v = video.query.filter_by(love_post_id=love_post['love_post_id']).first()
            love_post['videoUrl'] = getVideo(v.aliyun_video_id)

    love_post['is_collected'] = True if u_collection else False
    love_post['is_user_like'] = True if u_love_post_like else False
    is_fans = True if love_post_user_fans else False

    if len(love_comment) == 0:
        response= jsonify(
            error='No select data!', 
            love_post=love_post, 
            love_post_user=love_post_user,
            is_fans=is_fans,
            love_comments=[],
            love_comment_count=0
        )
        response.status_code = 200
        return response

    u_love_comment_like = userLoveCommentLike.query.filter_by(user_id=user.user_id).all()
    u_love_comment_like = [l.love_post_comment_id for l in u_love_comment_like]

    love_comments = [l.to_json() for l in love_comment]
    for love_comment in love_comments:
        user = User.query.get(love_comment['user_id'])
        love_comment['nickName'] = user.nickName
        love_comment['avatarUrl'] = user.avatarUrl
        if love_comment['reply_user_id']:
            love_comment['reply_user_nickName'] = User.query.get(love_comment['reply_user_id']).nickName
        
        love_comment['is_user_like'] = True if love_comment['love_post_comment_id'] in u_love_comment_like else False

    print('[*] Get love post detail')
    response = jsonify(
        message='Get love comment data successfully!', 
        love_post=love_post, 
        love_comments=love_comments, 
        love_comment_count=love_post['review'],
        love_post_user=love_post_user,
        is_fans=is_fans
    )
    response.status_code = 200
    return response


# √
# 增加表白墙评论喜欢数
@api.route('/loveCommentLike/<lovePostCommentId>', methods=['POST'])
def add_love_comment_like(lovePostCommentId):
    u_love_comment_like = userLoveCommentLike(user_id=g.current_user.user_id, love_post_comment_id=lovePostCommentId)
    try:
        db.session.add(u_love_comment_like)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error="Add like successfully failed!", detail=traceback.format_exc())
        response.status_code = 403
        return response
        
    print('[+] Add love comment: %r like' % u_love_comment_like.love_post_comment_id)
    response = jsonify(message='Add like successfully!')
    response.status_code = 200
    return response

# √
# 减少表白墙评论喜欢数
@api.route('/loveCommentLike/<lovePostCommentId>', methods=['DELETE'])
def change_love_comment_like(lovePostCommentId):
    u_love_comment_like = userLoveCommentLike.query.filter(userLoveCommentLike.user_id==g.current_user.user_id, \
                                                            userLoveCommentLike.love_post_comment_id==lovePostCommentId).first_or_404()
    try:
        db.session.delete(u_love_comment_like)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error="Delete like failed!", detail=traceback.format_exc())
        response.status_code = 403
        return response

    print('[-] Delete love comment: %r like' % u_love_comment_like.love_post_comment_id)
    response = jsonify(message='Delete like successfully!')
    response.status_code = 200
    return response